#include "commandrunner.h"
#include "databasemanager.h"
#include <QDebug>
#include <QFileInfo>
#include <QDir>

// CommandTask 实现
CommandTask::CommandTask(const QString &commandId, 
                         const QString &command, 
                         const QString &folderId, 
                         const QString &filePath, 
                         const QString &params,
                         DatabaseManager *databaseManager)
    : m_commandId(commandId)
    , m_command(command)
    , m_folderId(folderId)
    , m_filePath(filePath)
    , m_params(params)
    , m_databaseManager(databaseManager)
{
    setAutoDelete(true); // 任务完成后自动删除
}

void CommandTask::run()
{
    qDebug() << "开始执行命令，ID:" << m_commandId << "命令类型:" << m_command;
    
    // 更新状态为 running
    if (m_databaseManager) {
        m_databaseManager->updateCommandStatus(m_commandId, "running");
    }
    
    // 执行命令
    executeCommand();
    
    // 更新状态为 completed
    if (m_databaseManager) {
        m_databaseManager->updateCommandStatus(m_commandId, "completed");
        qDebug() << "命令执行完成，ID:" << m_commandId;
    }
}

void CommandTask::executeCommand()
{
    if (m_command == "uploadfile") {
        qDebug() << "执行上传文件命令，文件夹ID:" << m_folderId << "文件路径:" << m_filePath;
        // TODO: 实现上传文件的具体逻辑
        // 这里可以调用 BackendService 的上传方法
        // 目前只是模拟执行，实际需要根据业务需求实现
        QFileInfo fileInfo(m_filePath);
        if (fileInfo.exists()) {
            qDebug() << "文件存在，准备上传:" << m_filePath;
            // 实际的上传逻辑应该在这里实现
        } else {
            qDebug() << "文件不存在:" << m_filePath;
        }
    } else {
        qDebug() << "未知的命令类型:" << m_command;
    }
}

// CommandRunner 实现
CommandRunner::CommandRunner(QObject *parent)
    : QObject(parent)
    , m_databaseManager(nullptr)
    , m_timer(new QTimer(this))
    , m_threadPool(new QThreadPool(this))
    , m_threadPoolSize(5)
{
    // 设置线程池大小
    m_threadPool->setMaxThreadCount(m_threadPoolSize);
    
    // 设置定时器，每1秒检查一次
    m_timer->setInterval(1000);
    connect(m_timer, &QTimer::timeout, this, &CommandRunner::checkPendingCommands);
    
    qDebug() << "CommandRunner 初始化完成，线程池大小:" << m_threadPoolSize;
}

CommandRunner::~CommandRunner()
{
    stop();
}

void CommandRunner::setDatabaseManager(DatabaseManager *databaseManager)
{
    m_databaseManager = databaseManager;
    qDebug() << "CommandRunner 设置数据库管理器";
}

void CommandRunner::start()
{
    if (!m_databaseManager) {
        qDebug() << "CommandRunner 无法启动：数据库管理器未设置";
        return;
    }
    
    if (m_timer->isActive()) {
        qDebug() << "CommandRunner 已在运行";
        return;
    }
    
    m_timer->start();
    qDebug() << "CommandRunner 已启动，每1秒检查一次待处理命令";
}

void CommandRunner::stop()
{
    if (m_timer->isActive()) {
        m_timer->stop();
        qDebug() << "CommandRunner 已停止";
    }
    
    // 等待所有任务完成
    m_threadPool->waitForDone();
    qDebug() << "CommandRunner 所有任务已完成";
}

void CommandRunner::setThreadPoolSize(int size)
{
    if (size > 0 && size <= 100) {
        m_threadPoolSize = size;
        m_threadPool->setMaxThreadCount(size);
        qDebug() << "CommandRunner 线程池大小设置为:" << size;
    } else {
        qDebug() << "无效的线程池大小:" << size << "，保持默认值5";
    }
}

void CommandRunner::checkPendingCommands()
{
    if (!m_databaseManager) {
        return;
    }
    
    processPendingCommands();
}

void CommandRunner::processPendingCommands()
{
    if (!m_databaseManager) {
        return;
    }
    
    // 查询待处理的命令
    QList<QMap<QString, QVariant>> pendingCommands = m_databaseManager->queryPendingCommands();
    
    if (pendingCommands.isEmpty()) {
        return; // 没有待处理的命令
    }
    
    qDebug() << "发现" << pendingCommands.size() << "个待处理命令";
    
    // 检查线程池是否还有空闲线程
    int activeThreadCount = m_threadPool->activeThreadCount();
    int availableSlots = m_threadPoolSize - activeThreadCount;
    
    if (availableSlots <= 0) {
        qDebug() << "线程池已满，等待下一次检查";
        return;
    }
    
    // 处理待处理的命令（最多处理可用线程数）
    int processCount = qMin(availableSlots, pendingCommands.size());
    
    for (int i = 0; i < processCount; ++i) {
        const QMap<QString, QVariant> &command = pendingCommands[i];
        
        QString commandId = command["id"].toString();
        QString commandType = command["command"].toString();
        QString folderId = command["folderId"].toString();
        QString filePath = command["filePath"].toString();
        QString params = command["params"].toString();
        
        // 创建任务并提交到线程池
        CommandTask *task = new CommandTask(commandId, commandType, folderId, filePath, params, m_databaseManager);
        m_threadPool->start(task);
        
        qDebug() << "提交命令到线程池，ID:" << commandId << "命令类型:" << commandType;
    }
}

